package com.denlaku.longan.handlers;

import com.denlaku.longan.util.JsonUtil;
import com.denlaku.longan.vo.ComponentGrid;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author tianx
 */
public class ComponentGridTypeHandler extends BaseTypeHandler<ComponentGrid> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, ComponentGrid componentGrid, JdbcType jdbcType) throws SQLException {
        if (componentGrid != null) {
            preparedStatement.setObject(i, JsonUtil.toJsonString(componentGrid));
        }
    }

    @Override
    public ComponentGrid getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String json = resultSet.getString(columnName);
        return parseObject(json);
    }

    @Override
    public ComponentGrid getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String json = resultSet.getString(columnIndex);
        return parseObject(json);
    }

    @Override
    public ComponentGrid getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String json = callableStatement.getString(columnIndex);
        return parseObject(json);
    }

    private ComponentGrid parseObject(String json) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        return JsonUtil.parseObject(json, ComponentGrid.class);
    }
}
